var wizPanels = new Object();

jQuery.fn.wizard = function(){
  var args = arguments[0] || {};

  if(args == 'open'){
	updateWizard(0, wizPanels[$(this).attr('id')]);
	$(this).dialog('open');
	return;
  }
  
  var steps = $(this).children('fieldset');
  var count = steps.size();

  wizPanels[$(this).attr('id')] = count;

  steps.each(function(i) {
    $(this).wrap("<div id='step" + i + "'></div>");
    $("#step" + i).hide();
  });
  
  var height = args.height || null;
  var width = args.width || null;
  
  return $(this).dialog({
    autoOpen: false,
    height: height,
    width: width,
    modal: true,
    title: args.title,
    buttons: [
      {
        id: "wizback",
        text: "Back",
        class: "green button",
        click: function(){}
      },
      {
        id: "wiznext",
        text: "Next",
        class: "green button",
        click: function(){}
      },
      {
        id: "wizfinish",
        text: "Finish",
        class: "green button",
        click: function(){
          $(this).dialog("close");
          args.finish();
        }
      }
    ],
    close: function() {
      steps.each(function(i) {
        $("#step" + i).hide();
      });
    }
  });
};

function updateWizard(i, total) {
  $("#step" + i).show();

  if (i == 0) {
    makeNext(i, total);
    makeBackDisabled(i);
    makeFinishDisabled(i);
  } else if (i == total-1) {
    makeNextDisabled(i);
    makeBack(i, total);
    makeFinish(i);
  } else {
    makeBack(i, total);
    makeNext(i, total);
    makeFinishDisabled(i);
  }
}

function makeBackDisabled(i) {
  $("#wizback")
    .fadeTo(0, 0.3)
    .attr('disabled', true)
    .addClass('disabled');
}

function makeBack(i, total) {
  $("#wizback")
    .fadeTo(0, 1)
    .attr('disabled', false)
    .removeClass('disabled')
    .unbind('click')
    .bind("click", function() {
      $("#step" + i).hide();
      updateWizard(i-1, total);
    });
}

function makeNextDisabled(i) {
  $("#wiznext")
    .fadeTo(0, 0.3)
    .attr('disabled', true)
    .addClass('disabled');
}

function makeNext(i, total) {
  $("#wiznext")
    .fadeTo(0, 1)
    .attr('disabled', false)
    .removeClass('disabled')
    .unbind('click')
    .bind("click", function() {
      $("#step" + i).hide();
      updateWizard(i+1, total);
    });
}

function makeFinishDisabled(i) {
  $("#wizfinish")
    .fadeTo(0, 0.3)
    .attr('disabled', true)
    .addClass('disabled');
}

function makeFinish(i) {
  $("#wizfinish")
    .fadeTo(0, 1)
    .attr('disabled', false)
    .removeClass('disabled');
}